package com.example.myapp.players;

import com.example.myapp.event.ClickOnCellEvent;
import com.example.myapp.event.ClickOnCellEventListener;
import com.example.myapp.utils.StateAnalysis;

import java.util.List;

public class HumanPlayer extends Player implements ClickOnCellEventListener{

    private int[] lastSelectedCell;
    List<int[]> capable;

    @Override
    public int[] getNextStep(int[] stateMatrix, int faction) {
        capable = StateAnalysis.listCapablePoints(getGame(), getFaction());
        if (capable.size() == 0) {
            return new int[]{-1, -1};
        }
        while (lastSelectedCell == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int[] result = new int[]{lastSelectedCell[0], lastSelectedCell[1]};
        lastSelectedCell = null;
        return result;
    }

    @Override
    public void clickOnCellEvent(ClickOnCellEvent event) {
        if (super.isMyTurn()) {
            int[] action = new int[]{event.getXi(), event.getYi()};
            if (isLegalInput(action)) {
                lastSelectedCell = action;
            } else {
                lastSelectedCell = null;
            }
        } else {
            lastSelectedCell = null;
        }
    }

    private boolean isLegalInput(int[] action) {
        if (capable != null && capable.size() > 0) {
            for (int[] ints : capable) {
                if (ints[0] == action[0] && ints[1] == action[1]) {
                    return true;
                }
            }
        }
        return false;//!(action[0] == -1 || action[1] == -1);
    }

    public HumanPlayer(int f) {
        super(f);
    }
}
